import base64
import hashlib
import hmac
import logging
import time
import urllib.parse
import requests
import requests.auth

from coin.exchange.base.kr_rest.auth_base import AuthKey
from coin.exchange.base.kr_rest.rest_client_base import RestUpdate
from coin.exchange.util.rate_limit import RateLimiter
from coin.exchange.util.async_http_client import create_async_http_client


OKEX_API_HOST = 'www.okex.com'


class OkexAuth(requests.auth.AuthBase):
  def __init__(self, key_file):
    self._key = AuthKey.from_file(key_file)
    self._key.passphrase = self._key.get_value('passphrase')

  def get_sign(self, str_to_be_signed):
    signature = hmac.new(self._key.secret_key_bytes,
                         str_to_be_signed.encode(),
                         digestmod=hashlib.sha256)
    signature = base64.b64encode(signature.digest()).decode()
    return signature

  def __call__(self, req: requests.PreparedRequest):
    assert req.method in ('GET', 'POST', 'DELETE'), req.method
    timestamp = '%.03f' % time.time()
    parsed_result = urllib.parse.urlparse(req.url)
    if req.method == 'GET' and parsed_result.query:
      path = parsed_result.path + '?' + parsed_result.query
    else:
      path = parsed_result.path

    body = req.body.decode() if req.body else ''
    str_to_be_signed = ''.join([timestamp, req.method, path, body])
    headers = {
        'OK-ACCESS-KEY': self._key.access_key,
        'OK-ACCESS-SIGN': self.get_sign(str_to_be_signed),
        'OK-ACCESS-TIMESTAMP': timestamp,
        'OK-ACCESS-PASSPHRASE': self._key.passphrase,
        'Content-Type': 'application/json',
    }
    req.headers.update(headers)
    return req


class OkexSyncQueryer(object):
  def __init__(self, key_file, *, api_host=None, disable_ssl=False, timeout=10):
    self._timeout = timeout
    self._auth = OkexAuth(key_file) if key_file else None
    scheme = 'http://' if disable_ssl else 'https://'
    self._api_host = scheme + (api_host or OKEX_API_HOST)
    self.rate_limit = RateLimiter(100, 10)
    self._logger = logging.getLogger(__name__)

  def auth_request(self, method, path, params):
    assert method in ('GET', 'POST', 'DELETE'), method
    url = urllib.parse.urljoin(self._api_host, path)
    response = None
    data = None
    if method != 'GET':
      data = params
      params = None
    try:
      response = requests.request(method,
                                  url,
                                  params=params,
                                  json=data,
                                  auth=self._auth,
                                  timeout=self._timeout)
      content = response.json()
      return content
    except requests.exceptions.RequestException:
      self._logger.exception('RequestException: %s')
      raise
    except ValueError:
      self._logger.exception('Json decode: %s', response.content)
      raise
    except Exception as e:
      self._logger.exception('Unknown exception, %s', e)
      raise

  def _query_nocheck(self, method, path, params):
    req_timestamp = time.time()
    content = self.auth_request(method, path, params)
    res_timestamp = time.time()
    status = requests.codes.ok
    update = RestUpdate(req_timestamp, res_timestamp, content, status)
    return update

  def query(self, method, path, params=None, disable_rate_limit=False):
    if not disable_rate_limit:
      while not self.rate_limit.check():
        time.sleep(0.1)
    else:
      self.rate_limit.check()
    return self._query_nocheck(method, path, params)


class OkexAsyncQueryer(object):
  def __init__(
      self,
      key_file,
      *,
      api_host=None,
      disable_ssl=False,
      timeout=10,
      max_connections=4,
      rest_lib='pycurl',
  ):
    self._timeout = timeout
    self._http_client = create_async_http_client(rest_lib=rest_lib, max_connections=max_connections)
    self._auth = OkexAuth(key_file) if key_file else None
    scheme = 'http://' if disable_ssl else 'https://'
    self._api_host = scheme + (api_host or OKEX_API_HOST)

  def query(self, method, path, params=None):
    assert method in ('GET', 'POST', 'DELETE'), method
    data = None
    if method != 'GET':
      data = params
      params = None

    url = urllib.parse.urljoin(self._api_host, path)
    future = self._http_client.fetch(method=method,
                                     url=url,
                                     params=params,
                                     json=data,
                                     auth=self._auth,
                                     timeout=self._timeout)
    return future


class OkexNativePrivateClient(object):
  def __init__(
      self,
      *,
      key_file,
      api_host=None,
      disable_ssl=False,
      timeout=10,
      max_connections=8,
      use_async=False,
      rest_lib='pycurl',
  ):
    rest_lib = rest_lib or None
    if use_async:
      self._auth_queryer = OkexAsyncQueryer(key_file,
                                            api_host=api_host,
                                            disable_ssl=disable_ssl,
                                            timeout=timeout,
                                            max_connections=max_connections,
                                            rest_lib=rest_lib)
    else:
      self._auth_queryer = OkexSyncQueryer(key_file, api_host=api_host, timeout=timeout)

  def _query(self, method, path, params=None):
    if params is not None:
      params = {key: value for key, value in params.items() if value is not None}
    params = params or None
    return self._auth_queryer.query(method, path, params=params)

  def query_wallet(self):
    method = 'GET'
    path = '/api/v5/asset/balances'
    update = self._query(method, path)
    return update

  def query_accounts(self):
    method = 'GET'
    path = '/api/v5/account/balance'
    update = self._query(method, path)
    return update

  def query_withdraw_history(self, currency):
    method = 'GET'
    path = '/api/v5/asset/withdrawal-history'
    params = {'ccy': currency}
    update = self._query(method, path, params)
    return update

  def query_deposit_history(self, currency):
    method = 'GET'
    path = '/api/v5/asset/deposit-history'
    params = {'ccy': currency}
    update = self._query(method, path, params)
    return update
